import 'package:dio/dio.dart';
import '../../constants/app_constants.dart';
import '../../exceptions/app_exceptions.dart';

class ErrorInterceptor extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    AppException exception;
    
    switch (err.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        exception = TimeoutException(
          message: '请求超时，请检查网络连接',
          code: AppConstants.errorCodeTimeout,
          details: err.message,
        );
        break;
        
      case DioExceptionType.badResponse:
        final statusCode = err.response?.statusCode ?? 0;
        final message = _getErrorMessage(statusCode, err.response?.data);
        
        if (statusCode == 401) {
          exception = AuthException(
            message: message,
            code: statusCode,
            details: err.response?.data?.toString(),
          );
        } else if (statusCode == 403) {
          exception = AuthException(
            message: message,
            code: statusCode,
            details: err.response?.data?.toString(),
          );
        } else if (statusCode == 404) {
          exception = ServerException(
            message: message,
            code: statusCode,
            details: err.response?.data?.toString(),
          );
        } else if (statusCode >= 500) {
          exception = ServerException(
            message: message,
            code: statusCode,
            details: err.response?.data?.toString(),
          );
        } else {
          exception = NetworkException(
            message: message,
            code: statusCode,
            details: err.response?.data?.toString(),
          );
        }
        break;
        
      case DioExceptionType.cancel:
        exception = CancelException(
          message: '请求已取消',
          code: AppConstants.errorCodeCancel,
          details: err.message,
        );
        break;
        
      case DioExceptionType.connectionError:
        exception = NetworkException(
          message: '网络连接失败，请检查网络设置',
          code: AppConstants.errorCodeNetwork,
          details: err.message,
        );
        break;
        
      case DioExceptionType.badCertificate:
        exception = NetworkException(
          message: 'SSL证书验证失败',
          code: AppConstants.errorCodeNetwork,
          details: err.message,
        );
        break;
        
      case DioExceptionType.unknown:
      default:
        exception = UnknownException(
          message: '未知错误',
          code: AppConstants.errorCodeUnknown,
          details: err.message,
        );
        break;
    }
    
    handler.reject(
      DioException(
        requestOptions: err.requestOptions,
        response: err.response,
        type: err.type,
        error: exception,
        message: exception.message,
      ),
    );
  }

  String _getErrorMessage(int statusCode, dynamic responseData) {
    // 尝试从响应中获取错误信息
    if (responseData is Map<String, dynamic>) {
      final message = responseData['message'] as String?;
      if (message != null && message.isNotEmpty) {
        return message;
      }
      
      final error = responseData['error'] as String?;
      if (error != null && error.isNotEmpty) {
        return error;
      }
    }
    
    // 根据状态码返回默认错误信息
    switch (statusCode) {
      case 400:
        return '请求参数错误';
      case 401:
        return '未授权，请重新登录';
      case 403:
        return '权限不足';
      case 404:
        return '请求的资源不存在';
      case 405:
        return '请求方法不允许';
      case 408:
        return '请求超时';
      case 409:
        return '请求冲突';
      case 422:
        return '数据验证失败';
      case 429:
        return '请求过于频繁';
      case 500:
        return '服务器内部错误';
      case 502:
        return '网关错误';
      case 503:
        return '服务不可用';
      case 504:
        return '网关超时';
      default:
        return '请求失败 (错误码: $statusCode)';
    }
  }
}